package com.soboot.common.config.job.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.soboot.common.config.job.XxlJobInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Author:
 * @createTime: 2023年01月28日 21:40:32
 * @version:
 * @Description: 执行任务service
 * @Copyright:
 */
@Lazy
@Service
public class JobInfoService {

    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;

    @Autowired
    private JobLoginService jobLoginService;

    /**
     *
     * @param jobGroupId 执行器id
     * @param executorHandler
     * @return
     */
    public List<XxlJobInfo> getJobInfo(Integer jobGroupId, String executorHandler) {

        String url = adminAddresses+"/jobinfo/pageList";
        HttpResponse response = HttpRequest.post(url)
                .form("jobGroup", jobGroupId)
                .form("executorHandler", executorHandler)
                .form("triggerStatus", -1)
                .cookie(jobLoginService.getCookie())
                .execute();

        String body = response.body();
        JSONArray array = JSONObject.parseObject(body).getJSONArray("data");
        List<XxlJobInfo> list = array.toJavaList(XxlJobInfo.class);
        return list;
    }

    /**
     * 添加新的任务
     * @param xxlJobInfo
     * @return
     */
    public Integer addJobInfo(XxlJobInfo xxlJobInfo) {

        String url = adminAddresses+"/jobinfo/add";

        Map<String, Object> paramMap = BeanUtil.beanToMap(xxlJobInfo);
        HttpResponse response = HttpRequest.post(url)
                .form(paramMap)
                .cookie(jobLoginService.getCookie())
                .execute();

        JSON json = JSONUtil.parse(response.body());
        Object code = json.getByPath("code");
        if (code.equals(HttpStatus.HTTP_OK)){
            return Convert.toInt(json.getByPath("content"));
        }
        throw new RuntimeException("add jobInfo error!");
    }
}
